﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Configuration;

namespace Nova_Common
{
    public class LogManager
    {
        private static readonly int DelLogDay = Convert.ToInt32(ConfigurationManager.AppSettings["DelLogDay"]);// 90天;
        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="sResult"></param>
        /// <param name="sFunctionName"></param>
        /// <param name="sInfo"></param>
        public static void WriterLog(string sResult, string sFunctionName, string sInfo)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb = new StringBuilder();
                string sPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "");
                sb.Append(sPath);
                sb.Append("\\Logs\\");
                sb.Append(sFunctionName);
                sb.Append("_");
                sb.Append(DateTime.Now.ToString("yyyyMMdd"));
                sb.Append(".txt");

                StreamWriter sr = new StreamWriter(sb.ToString(), true);
                sr.WriteLine("\r\n==========================================\r\n");
                sr.WriteLine(DateTime.Now.ToString() + "\r\n" + sResult + "\r\n" + sInfo);
                sr.Close();


                //增加超期的文件删除 n天(配置文件中配置)前的一年内的全部删除
                for (int i = 0; i < 365; i++)
                {
                    string delLogFile = sPath + "\\Logs\\" + sFunctionName + "_" + DateTime.Now.AddDays(-DelLogDay - i).ToString("yyyyMMdd") + ".txt";
                    if (System.IO.File.Exists(delLogFile))
                    {
                        FileInfo fi = new FileInfo(delLogFile);
                        fi.Delete();
                        fi = null;

                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}
